//
//  FQDCommentViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 8/30/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDCommentViewController.h"
#import "FQDRegisterNavViewController.h"
#import "FQDPraiseHistory.h"
#import "FQDArticleCommentCellItemProvider.h"
#import "FQDRefreshFooter.h"
#import "FQDCommentCell.h"
#import "FQDQIconEmptyView.h"
#import "FQDCommentInputBar.h"
#import "UIImage+ImageEffects.h"
#import "UIView+FQDExtension.h"
#import "FQDRestModel.h"
#import "QDailyAPI.h"
#import "FQDAccountManager.h"

#import "Masonry.h"

@interface FQDCommentViewController () <UITableViewDataSource,
                                        UITableViewDelegate,
                                        UIGestureRecognizerDelegate,
                                        FQDCommentInputBarDelegate,
                                        FQDCommentCellDelegate>

// 顶部评论条数label
@property (nonatomic, strong) UILabel *commentCountLabel;
// 返回按钮
@property (nonatomic, strong) UIButton *backButton;
// 导航条分割线
@property (nonatomic, strong) UIView *separateLine;
// 评论tableView
@property (nonatomic, strong) UITableView *commentTableView;
// 输入框
@property (nonatomic, strong) FQDCommentInputBar *inputBar;
// 评论加载更多页脚
@property (nonatomic, strong) FQDRefreshFooter *refreshFooter;
// 评论数据源
@property (nonatomic, strong) FQDArticleCommentCellItemProvider *provider;
// 要回复的父级评论
@property (nonatomic, strong) FQDComment *replyParentComment;
// 无评论显示的空白页面
@property (nonatomic, strong) FQDQIconEmptyView *emptyView;

@end

@implementation FQDCommentViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupTopNavBar];
    [self setupCommentTableView];
    [self setupInputBar];
    [self setupRefreshView];
    [self setupQIconEmptyView];
    [self prepareConstraints];
    [self setupGestureRecognizers];
    [self setupCommentsProvider];
    [self loadNewComments];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(keyboardWillShow:)
                          name:UIKeyboardWillShowNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(keyboardWillHide:)
                          name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupCommentsProvider
{
    self.provider = [[FQDArticleCommentCellItemProvider alloc] init];
    self.provider.feedId = self.post.ID;
}

- (void)setupTopNavBar
{
    self.commentCountLabel = [[UILabel alloc] init];
    self.commentCountLabel.font = FQDRegularFontWithSize(17.0f);
    self.commentCountLabel.textAlignment = NSTextAlignmentCenter;
    self.commentCountLabel.backgroundColor = [UIColor whiteColor];
    self.commentCountLabel.text = [NSString stringWithFormat:@"%@条评论", @(self.post.comment_count)];
    [self.view addSubview:self.commentCountLabel];
    
    UIImage *backImage = [UIImage imageNamed:@"commentClose"];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    [self.view addSubview:self.backButton];
    
    [self.backButton addTarget:self action:@selector(goBack:) forControlEvents:UIControlEventTouchUpInside];
    
    self.separateLine = [[UIView alloc] init];
    self.separateLine.backgroundColor = RGB(204, 204, 204);
    [self.view addSubview:self.separateLine];
}

- (void)updateCommentCountLabel
{
    self.commentCountLabel.text = [NSString stringWithFormat:@"%@条评论", @(self.post.comment_count)];
}

- (void)setupCommentTableView
{
    self.commentTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.commentTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.commentTableView.dataSource = self;
    self.commentTableView.delegate = self;
    self.commentTableView.contentInset = UIEdgeInsetsMake(0, 0, 45.0f, 0);
    [self.view addSubview:self.commentTableView];
    [self.view sendSubviewToBack:self.commentTableView];
    
    [self.commentTableView registerClass:[FQDCommentCell class]
                  forCellReuseIdentifier:[FQDCommentCell reuseId]];
    
    self.commentTableView.estimatedRowHeight = 150.0f;
    self.commentTableView.rowHeight = UITableViewAutomaticDimension;
}


- (void)setupInputBar
{
    self.inputBar = [[FQDCommentInputBar alloc] init];
    self.inputBar.delegate = self;
    [self.view addSubview:self.inputBar];
    
    WeakSelf;
    [self.inputBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.and.right.equalTo(weakSelf.view);
    }];
}

- (void)setupRefreshView
{
    self.refreshFooter = [FQDRefreshFooter footerWithRefreshingTarget:self
                          refreshingAction:@selector(loadMoreComments)];
    self.commentTableView.mj_footer = self.refreshFooter;
}

- (void)setupQIconEmptyView
{
    self.emptyView = [[FQDQIconEmptyView alloc] init];
    self.emptyView.backgroundColor = [UIColor whiteColor];
    self.emptyView.hidden = YES;
    self.emptyView.titleText = @"你来留下第一条评论吧！";
    [self.view insertSubview:self.emptyView aboveSubview:self.commentTableView];
}

- (void)prepareConstraints
{
    WeakSelf;
    [self.commentCountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@64);
    }];
    
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(22);
        make.left.equalTo(weakSelf.view).offset(16);
        make.size.equalTo(@20);
    }];
    
    [self.separateLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.commentCountLabel.mas_bottom);
        make.left.and.right.equalTo(weakSelf.view);
        make.height.equalTo(@0.5);
    }];
    
    CGSize inputBarSize = self.inputBar.frame.size;
    [self.commentTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.commentCountLabel.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).offset(-inputBarSize.height);
    }];
    
    [self.emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.and.right.equalTo(weakSelf.commentTableView);
        make.height.equalTo(@284);
    }];
}

- (void)setupGestureRecognizers
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                             action:@selector(backgroundTapped:)];
    tapRecognizer.cancelsTouchesInView = NO;
    tapRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapRecognizer];
}

- (BOOL)checkLogined
{
    BOOL isLogined = [[FQDAccountManager sharedManager] isLogined];
    if (!isLogined) {
        FQDRegisterNavViewController *navController = [[FQDRegisterNavViewController alloc] init];
        navController.backgroundViewController = self;
        [self presentViewController:navController animated:YES completion:nil];
    }
    return isLogined;
}


- (BOOL)shouldShowEmpty
{
    BOOL hasFeeds = [self.provider.cellItems count] > 0;
    BOOL hasMoreCellItems = [self.provider hasMoreCellItems];
    return !hasFeeds && !hasMoreCellItems;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark - Event Response
- (void)goBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)loadNewComments
{
    WeakSelf;
    [self.provider loadNewCellItems:^(BOOL isSuccess) {
        [weakSelf.commentTableView reloadData];
        
        if (![weakSelf.provider hasMoreCellItems]) {
            [weakSelf.refreshFooter setHidden:YES];
        }
        weakSelf.emptyView.hidden = ![self shouldShowEmpty];
    }];
}

- (void)loadMoreComments
{
    WeakSelf;
    if ([self.provider hasMoreCellItems]) {
        [self.provider loadMoreCellItems:^(BOOL isSuccess) {
            [weakSelf.commentTableView reloadData];
            [weakSelf.refreshFooter endRefreshing];
            weakSelf.emptyView.hidden = ![self shouldShowEmpty];
        }];
    } else {
        [self.refreshFooter endRefreshingWithNoMoreData];
    }
}

#pragma mark - GestureRecognizers
- (void)backgroundTapped:(UIGestureRecognizer *)gr
{
    [self.inputBar endEditing:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    BOOL isTableViewDescendant = [touch.view isDescendantOfView:self.commentTableView];
    BOOL isControl = [touch.view isKindOfClass:[UIControl class]];
    return !(isTableViewDescendant || isControl);
}

#pragma mark - Notifications
- (void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self.inputBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-keyboardFrame.size.height);
    }];
    
    [UIView animateWithDuration:0.3f animations:^{
        [self.inputBar layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification *)note
{
    [self.inputBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
    }];
    
    [UIView animateWithDuration:0.3f animations:^{
        [self.inputBar layoutIfNeeded];
    }];
}

#pragma mark - FQDCommentInputBarDelegate
- (BOOL)inputBarShouldBeginEditing:(FQDCommentInputBar *)inputBar
{
    return [self checkLogined];
}

- (void)inputBar:(FQDCommentInputBar *)inputBar didClickedSendButton:(UIButton *)sendButton
{
    NSString *commentText = inputBar.commentTextView.text;
    NSString *parentCommentId = @"0";
    if (self.replyParentComment) {
        parentCommentId = self.replyParentComment.ID;
    }
    WeakSelf;
    [[QDailyAPI sharedAPI] commentArticle:self.post.ID content:commentText parentCommentId:parentCommentId completion:^(id responseObject, NSError *error) {
        NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
        if ([status integerValue] == 200) {
            id response = responseObject[@"response"];
            NSNumber *postCommentCount = response[@"comment_count"];
            NSNumber *postPraiseCount = response[@"praise_count"];
            weakSelf.post.comment_count = [postCommentCount integerValue];
            weakSelf.post.praise_count = [postPraiseCount integerValue];
            [weakSelf updateCommentCountLabel];
            
            id comment = response[@"comment"];
            FQDComment *newComment;
            if ([comment[@"parent_id"] integerValue] == 0) {
                newComment = [FQDComment yy_modelWithJSON:comment];
            } else {
                newComment = [FQDChildComment yy_modelWithJSON:comment];
            }
            [weakSelf.provider addNewComment:newComment];
            [weakSelf.commentTableView reloadData];
            
        }
    }];
    
    
    [inputBar setPlaceHolderText:@"添加评论..."];
}

#pragma mark - FQDCommentCellDelegate
- (void)commentCell:(FQDCommentCell *)commentCell didClickedLikeButton:(UIButton *)likeButton comment:(FQDComment *)comment
{
    FQDPraiseHistory *praiseHistory = [FQDPraiseHistory sharedHistory];
    
    FQDAccountManager *accountManager = [FQDAccountManager sharedManager];
    NSString *userId = accountManager.currentUserId;
    
    NSInteger praiseCountBefore = comment.praise_count;
    BOOL praisedBefore = [praiseHistory userHasPraised:comment.ID userId:userId];
    BOOL praisedNow = !praisedBefore;
    FQDPraiseHistoryItem *praiseItem = [[FQDPraiseHistoryItem alloc] init];
    praiseItem.qdID = comment.ID;
    praiseItem.userId = userId;
    praiseItem.praised = praisedNow;
    praiseItem.praiseType = kPraiseTypeComment;
    
    WeakSelf;
    [[FQDPraiseHistory sharedHistory] praiseWithItem:praiseItem originalPraiseCount:praiseCountBefore updatePraiseCountBlock:^(NSInteger praiseCount) {
        comment.praise_count = praiseCount;
        [weakSelf.commentTableView reloadData];
    }];
}

#pragma mark - UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.provider.cellItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    FQDCommentCell *cell = (FQDCommentCell *)
    [tableView dequeueReusableCellWithIdentifier:[FQDCommentCell reuseId]];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.comment = self.provider.cellItems[indexPath.row];
    cell.delegate = self;
    
    return cell;
}

#pragma mark - UITableViewDeleagate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL isLogined = [self checkLogined];
    if (isLogined) {
        self.replyParentComment = self.provider.cellItems[indexPath.row];
        NSString *userName = self.replyParentComment.author.name;
        NSString *placeHolder = [NSString stringWithFormat:@"回复%@:", userName];
        [self.inputBar setPlaceHolderText:placeHolder];
        [self.inputBar.commentTextView becomeFirstResponder];
    }
}

@end
